/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.threemember;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.service.grant.RbacGrantMenuPermissionService;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.threemember.ThreeMemberAuthorizeService;
import com.je.servicecomb.CommonRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 三员角色授权
 */
@RestController
@RequestMapping("/je/rbac/threemember/authorize")
public class ThreeMemberAuthorizeController implements CommonRequestService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private ThreeMemberAuthorizeService threeMemberAuthorizeService;
    @Autowired
    private RbacGrantMenuPermissionService rbacGrantMenuPermissionService;

    /**
     * 加载角色树
     *
     * @return
     */
    @RequestMapping(value = "/loadTreeMemberRoleTree", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult installThreeMember() {
        List<DynaBean> memberBeanList = metaService.select("JE_RBAC_RESOURCESCOPE", ConditionsWrapper.builder().orderByDesc("SY_CREATETIME"));
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        List<String> roleIdList = new ArrayList<>();
        for (int i = 0; memberBeanList != null && i < memberBeanList.size(); i++) {
            roleIdList.add(memberBeanList.get(i).getStr("RESOURCESCOPE_ROLE_ID"));
        }

        List<DynaBean> roleBeanList = metaService.select("JE_RBAC_ROLE", ConditionsWrapper.builder().in("JE_RBAC_ROLE_ID", roleIdList));
        JSONTreeNode eachNode;
        for (int i = 0; roleBeanList != null && i < roleBeanList.size(); i++) {
            eachNode = new JSONTreeNode();
            eachNode.setId(roleBeanList.get(i).getStr("JE_RBAC_ROLE_ID"));
            eachNode.setText(roleBeanList.get(i).getStr("ROLE_NAME"));
            eachNode.setCode(roleBeanList.get(i).getStr("ROLE_CODE"));
            eachNode.setBean(roleBeanList.get(i).getValues());
            eachNode.setNodePath(roleBeanList.get(i).getStr("SY_PATH"));
            eachNode.setNodeInfo("角色");
            eachNode.setNodeInfoType("role");
            eachNode.setNodeType("LEAF");
            eachNode.setOrderIndex(String.valueOf(i));
            eachNode.setIcon("fal fa-user");
            eachNode.setParent("ROOT");
            eachNode.setTreeOrderIndex(roleBeanList.get(i).getStr("SY_TREEORDERINDEX"));
            rootNode.getChildren().add(eachNode);
        }
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 加载账号
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/loadAccount", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadAccount(HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        String start = getStringParameter(request, "start");
        String limit = getStringParameter(request, "limit");
        String orgId = getStringParameter(request, "orgId");
        String search = getStringParameter(request, "search");

        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择要查询的类型或标识！");
        }
        if (Strings.isNullOrEmpty(start)) {
            start = "0";
        }
        if (Strings.isNullOrEmpty(limit)) {
            limit = "30";
        }

        ConditionsWrapper wrapper = ConditionsWrapper.builder().table("JE_RBAC_VACCOUNTROLE").in("ACCOUNTROLE_ROLE_ID", Splitter.on(",").splitToList(ids));
        if (!Strings.isNullOrEmpty(orgId)) {
            wrapper.eq("SY_ORG_ID", orgId);
        }
        if (!Strings.isNullOrEmpty(search)) {
            wrapper.and(searchWrapper -> {
                searchWrapper.like("ACCOUNT_NAME", search);
            });
        }

        wrapper.orderByAsc("ORG_SY_ORDERINDEX", "AR_SY_ORDERINDEX", "ACCOUNTROLE_SY_CREATETIME");
        Page page = new Page(Integer.valueOf(start), Integer.valueOf(limit));
        List<Map<String, Object>> accountList = metaService.selectSql(page, wrapper);
        page.setRecords(accountList);
        return page == null ? BaseRespResult.successResultPage(Lists.newArrayList(), 0L) : BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    /**
     * 加载顶部菜单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/loadTopMenus"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadTopMenus(HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        return BaseRespResult.successResult(threeMemberAuthorizeService.loadTopMenus(ids));
    }

    @RequestMapping(value = {"/loadPermissionTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadPermissionTree(HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        String topMenuId = getStringParameter(request, "topMenuId");
        
        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择相关数据！");
        }
        if (Strings.isNullOrEmpty(topMenuId)) {
            return BaseRespResult.errorResult("请选择菜单模块！");
        }

        JSONTreeNode root = threeMemberAuthorizeService.loadMenuPermissions(ids, topMenuId);
        return BaseRespResult.successResult(root);
    }

    @RequestMapping(value = {"/saveRoleMenuPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult saveMenuPermission(HttpServletRequest request) {
        String roleIds = getStringParameter(request, "roleIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");
        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        //更新权限
        rbacGrantMenuPermissionService.updateRoleMenuPermissions(GrantTypeEnum.MENU, roleIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

}
